package com.qlk.vorder.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

import com.qlk.vorder.controller.base.JsonReader;
import com.qlk.vorder.controller.base.JsonResult;
import com.qlk.vorder.domain.enums.OrderCancelTypeEnum;
import com.qlk.vorder.domain.enums.OrderStatusEnum;
import com.qlk.vorder.domain.enums.PayStatusEnum;
import com.qlk.vorder.porxy.dto.QueryRefundResponse;
import com.qlk.vorder.utils.WorkBookObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.qlk.vorder.controller.base.BaseController;
import com.qlk.vorder.domain.Orders;
import com.qlk.vorder.domain.query.OrdersQuery;
import com.qlk.vorder.service.OrdersService;
import com.qlk.vorder.utils.exceptions.ExistedException;
import com.qlk.common.utils.page.PageUtil;
import com.qlk.common.utils.wrap.WrapMapper;
import com.qlk.common.utils.wrap.Wrapper;

import javax.servlet.http.HttpServletResponse;

/**
 * OrdersController ：咨询订单控制器
 * 
 * @author zhaoyanan
 * @version 2016-7-28 14:14:00
 */
@Controller
@RequestMapping("orders")
public class OrdersController extends BaseController {

	@Autowired
	private OrdersService ordersService;

	/** 视图前缀 */
	private static final String viewPrefix = "orders";

	private static final Log LOG = LogFactory.getLog(OrdersController.class);

	/**
	 * 分页 查询数据
	 * 
	 * @param model
	 * @param page
	 * @param query
	 * @return
	 */
	@RequestMapping(value = "")
	public String index(Model model, PageUtil page, OrdersQuery query) {
		String orderid="";
		try {
			orderid = query.getOrderid();
			if(StringUtils.isNotBlank(orderid)){
                List<String> list = Arrays.asList(orderid.split("\r\n"));
                query.setOrderIds(list);
			}
			List<Orders> dataList = ordersService.queryOrdersListWithPage(query, page);
            if (org.apache.commons.collections.CollectionUtils.isNotEmpty(dataList)){
                //存储默认加载订单信息
                model.addAttribute("defaultOrder",dataList.get(0));
            }
            query.setOrderid(orderid);
            //订单状态
            List<Map<String, Object>> orderStatus = OrderStatusEnum.getList();
            Map<Integer, String> orderStatusMap = OrderStatusEnum.getMap();
            Map<Integer, String> payStatusMap = PayStatusEnum.getMap();
            Map<Integer, String> cancelTypeMap = OrderCancelTypeEnum.getMap();
            model.addAttribute("orderStatus", orderStatus);
            model.addAttribute("orderStatusMap", orderStatusMap);
            model.addAttribute("payStatusMap", payStatusMap);
            model.addAttribute("cancelTypeMap", cancelTypeMap);
			model.addAttribute("dataList", dataList);// 数据集合
			model.addAttribute("query", query);// 查询参数
			model.addAttribute("page", page);// 分页
		} catch (Exception e) {
			LOG.error("orders index has error.", e);
		}
		return viewPrefix + "/index";
	}


    /**
     * 通过订单号查询明细
     * @param model
     * @param orderid
     * @return
     */
    @RequestMapping(value = "/queryOrderByNo", method = RequestMethod.POST)
    @ResponseBody
    public JsonResult queryOrderByNo(Model model, String orderid) {

        JsonResult jsonResult = new JsonResult();
        try {
//            List<ReserveSession> dataList = reserveSessionService.queryReserveSessionListWithPage(reserveSessionQuery, pageUtil);
            OrdersQuery ordersQuery = new OrdersQuery();
            ordersQuery.setOrderid(orderid);
            List<Orders> dataList = ordersService.queryOrdersList(ordersQuery);
            if (org.apache.commons.collections.CollectionUtils.isNotEmpty(dataList)){
                jsonResult.setCode(Wrapper.SUCCESS_CODE);
                jsonResult.setResult(dataList.get(0));
            }

        } catch (Exception e) {
            LOG.error("OrdersController--> queryOrderByNo 查询数据异常", e);
            jsonResult.setCode(JsonResult.CODE_SERVER_ERROR);
        }
        return jsonResult;
    }



	/**
	 * 咨询订单----添加跳转
	 * 
	 * @return
	 */
	@RequestMapping(value = "addForward")
	public String addForward() {
		return viewPrefix + "/add";
	}

	/**
	 * 咨询订单----添加
	 * 
	 * @param orders
	 * @return
	 */
	@RequestMapping(value = "add")
	@ResponseBody
	public Wrapper<?> add(Orders orders) {
		try {
			// orders.setCreateUser(getLoginUserCnName());
			if (ordersService.insert(orders)) {
				return WrapMapper.wrap(Wrapper.SUCCESS_CODE, "添加成功！");
			} else {
				return WrapMapper.wrap(Wrapper.ERROR_CODE, "添加失败！");
			}
		} catch (ExistedException e) {
			LOG.warn("orders add fail, exist orders.");
			return WrapMapper.wrap(Wrapper.ERROR_CODE, "添加失败，已经存在");
		} catch (Exception e) {
			LOG.error("orders add has error.", e);
			return WrapMapper.wrap(Wrapper.ERROR_CODE, "添加失败！");
		}
	}

	/**
	 * 咨询订单----更新跳转
	 * 
	 * @param model
	 * @param orders
	 * @return
	 */
	@RequestMapping(value = "updateForward")
	public String updateForward(Model model, Orders orders) {
		try {
			Orders ordersResult = ordersService.getOrdersById(orders.getId());
			model.addAttribute("orders", ordersResult);
		} catch (Exception e) {
			LOG.error("orders updateForward has error.", e);
		}
		return viewPrefix + "/update";
	}

	/**
	 * 咨询订单----更新
	 * 
	 * @param model
	 * @param orders
	 * @return
	 */
	@RequestMapping(value = "update")
	@ResponseBody
	public Wrapper<?> update(Model model, Orders orders) {
		try {
			// orders.setUpdateUser(getLoginUserCnName());
			if (ordersService.update(orders)) {
				return WrapMapper.wrap(Wrapper.SUCCESS_CODE, "更新成功！");
			} else {
				return WrapMapper.wrap(Wrapper.ERROR_CODE, "更新失败！");
			}
		} catch (Exception e) {
			LOG.error("orders update has error.", e);
			return WrapMapper.error();
		}
	}

	/**
	 * 咨询订单----删除
	 * 
	 * @param orders
	 * @return
	 */
	@RequestMapping(value = "delete")
	@ResponseBody
	public Wrapper<?> delete(Orders orders) {
		try {
			// orders.setUpdateUser(getLoginUserCnName());
			if (ordersService.delete(orders)) {
				return WrapMapper.wrap(Wrapper.SUCCESS_CODE, "删除成功！");
			} else {
				return WrapMapper.wrap(Wrapper.ERROR_CODE, "删除失败！");
			}
		} catch (Exception e) {
			LOG.error("orders delete has error.", e);
			return WrapMapper.error();
		}
	}

	/**
	 * 咨询订单----查询-无分页
	 * 
	 * @param query
	 * @return
	 */
	@RequestMapping(value = "query")
	@ResponseBody
	public Wrapper<?> query(OrdersQuery query) {
		try {
			List<Orders> list = ordersService.queryOrdersList(query);
			if (!CollectionUtils.isEmpty(list)) {
				return WrapMapper.wrap(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE, list);
			} else {
				return WrapMapper.wrap(Wrapper.ERROR_CODE, "查询配置信息失败！");
			}
		} catch (Exception e) {
			LOG.error("orders query has error.", e);
			return WrapMapper.error();
		}
	}

	/**
	 * 查询咨询订单详情
	 * 
	 * @param query
	 * @return
	 */
	@RequestMapping(value = "detail", method = RequestMethod.GET)
	@ResponseBody
	public Wrapper<?> detail(OrdersQuery query) {
		if (null == query || null == query.getId()) {
			return illegalArgument();
		}

		try {
			Orders orders = ordersService.getOrdersById(query.getId());
			if (orders != null) {
				return new Wrapper<Orders>().result(orders);
			} else {
				return WrapMapper.wrap(Wrapper.ERROR_CODE, "查询咨询订单详情失败！");
			}
		} catch (Exception e) {
			LOG.warn("detail orders has error.", e);
			return error();
		}
	}


    /**
     * 下载订单列表
     *
     * @param response
     * @param query
     */
    @RequestMapping(value = "downloadOrderList")
    public void downloadOrderList(HttpServletResponse response, OrdersQuery query) {

        OutputStream os = null;
        try {
            List<Orders> list = null;
            try {
                list = ordersService.queryOrdersListForDownLoad(query);
            } catch (Exception e) {
                this.logger.error("根据条件查询订单信息数据：", e);
            }
            os = response.getOutputStream();
            String filename = "订单数据.xls";
            response.setContentType("application/vnd.ms-excel");
            response.addHeader("Content-Disposition", "attachment; filename=\"" + new String(filename.getBytes("GB2312"), "ISO8859-1") + "\"");

            WorkBookObject wb = new WorkBookObject(filename);
            wb.addTitle(new String[]{"咨询订单号", "咨询医生名称", "预约咨询时间", "会员名称", "会员手机", "支付金额",
                    "订单状态", "支付状态"});

            //wb.saveTitle();//添加标题
            wb.setTitleStyle();//设置标题格式

            if (org.apache.commons.collections.CollectionUtils.isNotEmpty(list)) {

                String[] tAttrs = new String[]{"orderid", "drName", "reserveTime", "patientName", "patientMobile",
                        "orderPrice", "orderStatusName", "payStatusName"};

                wb.saveDataList(list, Orders.class, tAttrs);
            }
            wb.getWb().write(os);
            os.flush();
        } catch (Exception e) {
            this.logger.error("根据条件查询商品预览信息数据异常：", e);
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                this.logger.error("关闭数据流 ERROR", e);
            }
        }
    }


    /**
     * 查询退款单信息
     * @param model
     * @param rows
     * @param page
     * @param orderid
     * @return
     */
    @RequestMapping(value = "/queryRefund", method = RequestMethod.POST)
    @ResponseBody
    public JsonReader queryRefund(Model model, Integer rows, Integer page, String orderid) {
        JsonReader result = new JsonReader();
        PageUtil pageUtil = new PageUtil();
        pageUtil.setPageSize(rows);
        pageUtil.setCurPage(page);

        try {
//            List<ReserveSession> dataList = reserveSessionService.queryReserveSessionListWithPage(reserveSessionQuery, pageUtil);
            List<QueryRefundResponse> dataList = ordersService.getRefundListByOrderid(orderid);
            result.setCurrpage(pageUtil.getCurPage());
            result.setTotalpages(pageUtil.getTotalPage());
            result.setTotalrecords(pageUtil.getTotalRow());
            result.setResult(dataList);

        } catch (Exception e) {
            LOG.error("ordersController--> queryRefund 查询数据异常", e);
            result.setCode(JsonResult.CODE_SERVER_ERROR);
        }
        return result;
    }





}
